<template>
  <div>
    <el-button type="danger" size="mini" @click="batchDelete">批量删除</el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="id"
      :default-expanded-keys="expandedKey"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <=1"
            type="text"
            size="mini"
            @click="() => append(data)"
          >Append</el-button>
          <el-button type="text" size="mini" @click="edit(data)">edit</el-button>
          <el-button
            v-if="node.childNodes.length==0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >Delete</el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="category.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  data() {
    return {
      pid: [],
      updateNodes: [],
      title: "",
      dialogType: "", //edit,add
      category: {
        title: "",
        parentId: 0,
        sort: 0,
        id: null
      },
      dialogVisible: false,
      menus: [],
      expandedKey: [],
      defaultProps: {//node节点的属性，需要与对应的字段绑定
        children: "children",
        label: "title"
      }
    };
  },

  created(){
    this.getMenus()
  },

  methods: {
    //获取菜单数据
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/route/category/list/tree"),
        method: "get"
      }).then(({ data }) => {
        console.log("成功获取到菜单数据...", data.data);
        this.menus = data.data.list;
      });
    },
    //批量删除
    batchDelete() {
      let ids = [];
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      console.log("被选中的元素", checkedNodes);
      for (let i = 0; i < checkedNodes.length; i++) {
        ids.push(checkedNodes[i].id);
      }
      this.$confirm(`是否批量删除【${ids}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl("/route/category/delete"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          this.$message({
            message: "菜单批量删除成功",
            type: "success"
          });
          this.getMenus();
        });
      }).catch(() => {});
    },
    //点击append，初始化数据
    append(data) {
      console.log("append", data);
      this.dialogType = "add";
      this.title = "添加分类";
      this.dialogVisible = true;
      this.category.parentId = data.id;
      this.category.id = null;
      this.category.title = "";
      this.category.sort = 0;
    },
    //点击修改节点时回显数据
    edit(data) {
      console.log("要修改的数据", data);
      this.dialogType = "edit";
      this.title = "修改分类";
      this.dialogVisible = true;

      //发送请求获取当前节点最新的数据（确保是最新数据）
      this.$http({
        url: this.$http.adornUrl(`/route/category/getCategoryById/${data.id}`),
        method: "get"
      }).then(({ data }) => {
        //请求成功
        console.log("要回显的数据", data);
        this.category.title = data.data.category.title;
        this.category.id = data.data.category.id;
        this.category.parentId = data.data.category.parentId;
        this.category.sort = data.data.category.sort;
      });
    },

    //提交数据调用的方法
    submitData() {
      if (this.dialogType == "add") {
        this.addCategory();
      }
      if (this.dialogType == "edit") {
        this.editCategory();
      }
    },
    //修改节点
    editCategory() {
      var { id, title, sort } = this.category;
      this.$http({
        url: this.$http.adornUrl("/route/category/updateCategory"),
        method: "post",
        data: this.$http.adornData({ id, title, sort }, false)
      }).then(({ data }) => {
        this.$message({
          message: "菜单修改成功",
          type: "success"
        });
        //关闭对话框
        this.dialogVisible = false;
        //设置需要默认展开的菜单
        this.expandedKey = [this.category.parentId];
        //刷新出新的菜单
        this.getMenus();
      });
    },
    //添加节点
    addCategory() {
      console.log("提交的三级分类数据", this.category);
      this.$http({
        url: this.$http.adornUrl("/route/category/addCategory"),
        method: "post",
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.$message({
          message: "菜单保存成功",
          type: "success"
        });
        //关闭对话框
        this.dialogVisible = false;
        //设置需要默认展开的菜单
        console.log(this.category.parentId)
        this.expandedKey = [this.category.parentId];
        //刷新出新的菜单
        this.getMenus();
      });
    },

    //移除节点
    remove(node, data) {
      var ids = [data.id];
      this.$confirm(`是否删除【${data.title}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl("/route/category/delete"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          this.$message({
            message: "菜单删除成功",
            type: "success"
          });
          //刷新出新的菜单
          this.getMenus();
          //设置需要默认展开的菜单
          this.expandedKey = [node.parent.data.id];
        });
      }).catch(() => {});
    }
  },
};
</script>
<style scoped>
</style>